package threading_webserver;

import java.io.IOException;
import java.util.logging.Level;

public class Threading {

    private static Server webserver;
    private static Server controlserver;

    private static PortListener listener;

    private static ServerView web_gui;
    private static ServerView control_gui;

    private static Logger logger;

    public static void main(String[] args) throws Exception {
        web_gui = new ServerView("Webserver");
        control_gui = new ServerView("Controlserver");
        logger = new Logger();
        
//        DatabaseConnector.AddUser("Koen", "hallo", 1);
//        DatabaseConnector.AddUser("Erik", "hoi", 1);
//        DatabaseConnector.AddUser("Tester", "test", 2);

        Settings.setSettingsFromXML();

        listener = new PortListener() {
            @Override
            public void createNewWebServer() {
                if (webserver.getOutput() == null) {
                    createWebserver();
                } else if (webserver.getOutput().size() != 0) {
                    try {
                        webserver.getOutput().close();
                        createWebserver();
                    } catch (IOException ex) {
                        java.util.logging.Logger.getLogger(Threading.class.getName()).log(Level.SEVERE, null, ex);
                    }
                }
            }

            @Override
            public void createNewControlServer() {
                if (controlserver.getOutput() == null) {
                    createControlserver();
                } else if (controlserver.getOutput().size() != 0) {
                    try {
                        controlserver.getOutput().close();
                        createControlserver();
                    } catch (IOException ex) {
                        java.util.logging.Logger.getLogger(Threading.class.getName()).log(Level.SEVERE, null, ex);
                    }
                }
            }
        };

        //create the server
        createWebserver();
        createControlserver();
    }

    private static void createWebserver() {
        if(webserver != null)
        {
            webserver.deleteServersocket();
            webserver = null;
        }
        webserver = new Server("WebServer", Settings.webPort, web_gui, listener, logger);
    }

    private static void createControlserver() {
        if(controlserver != null)
        {
            controlserver.deleteServersocket();
            controlserver = null;
        }
        controlserver = new Server("ControlServer", Settings.controlPort, control_gui, listener, logger);
    }

}
